import axios from 'axios'
import { BASE_URL } from './url'
import { removeToken, getToken } from './auth'

// 创建axios示例
const request = axios.create({
  baseURL: BASE_URL,
  timeOut: 10000
})
request.interceptors.request.use(config => {
  const { url } = config
  // 判断请求url路径
  if (
    url.startsWith('/user') &&
    !url.startsWith('/user/login') &&
    !url.startsWith('/user/registered')
  ) {
    // 添加请求头
    config.headers.Authorization = getToken()
  }
  return config
})
request.interceptors.response.use(response => {
  const { status } = response.data
  if (status === 400) {
    // 此时，说明 token 失效，直接移除 token 即可
    removeToken()
  }
  return response
})
export default request
